<?php

namespace EasyDB\Tools;

class Arrays
{
    /**
     * 处理无限级分类，返回带有层级关系的树形结构
     * @param array $data 数据数组
     * @param int $root 根节点的父级id
     * @param string $id id字段名
     * @param string $pid 父级id字段名
     * @param string $children 树形结构子级字段名
     * @return array $tree 树形结构数组
     */
    public static function getMultilevelTree(array $data, $root = 0, $id = 'id', $pid = 'pid', $children = 'children')
    {
        $tree = [];
        $temp = [];

        foreach ($data as $key => $val) {
            $temp[$val[$id]] = &$data[$key];
        }
        foreach ($data as $key => $val) {
            $parentId = $val[$pid];
            if ($root == $parentId) {
                $tree[] = &$data[$key];
            } else {
                if (isset($temp[$parentId])) {
                    $parent              = &$temp[$parentId];
                    $parent[$children][] = &$data[$key];
                }
            }
        }
        return $tree;
    }
}
